package com.bdbit.ChargingStation.event;
import com.alibaba.fastjson.JSONObject;
import com.bdbit.ChargingStation.annotation.MqttListener;
import com.bdbit.ChargingStation.services.ChargingOrderService;
import com.bdbit.ChargingStation.services.DeviceOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 充电事件监听器
 * 负责处理各种充电相关事件，发送MQTT消息212
 */
@Slf4j
@Component
public class ChargingEventListener {
    @Autowired
    private ChargingOrderService chargingOrderService;
    @Autowired
    private DeviceOrderService deviceOrderService;

    /**
     * 处理开始充电事件
     */
    @MqttListener(topics = "${mqtt.charging-start-topic}")
    public void handleChargingStart(String message) {
        JSONObject payload = JSONObject.parseObject(message);
        String deviceId = payload.getString("device_id");
        String orderId = payload.getString("order_id");

        if (orderId != null && deviceId != null) {
            // 更新订单状态为“充电中”
            chargingOrderService.startCharging(Long.valueOf(orderId));

            // 绑定设备与订单
            deviceOrderService.bindDevice(deviceId, orderId);
        }
    }

    @MqttListener(topics = "${mqtt.status-update-topic}")
    public void handleStatusUpdate(String message) {
        JSONObject payload = JSONObject.parseObject(message);
        String deviceId = payload.getString("device_id");
        String status = payload.getString("status");

        log.info("收到设备状态更新: deviceId={}, status={}", deviceId, status);
        // 可用于更新设备状态、订单状态、或触发告警等逻辑
    }
    /**
     * 处理断电事件
     */
    @EventListener
    public void handlePowerOutageEvent(PowerOutageEvent event) {
        log.info("收到断电事件: {}", event.getEventType());
        String orderId = event.getOrderId();
        String eleCode = event.getEleCode();

        log.info("处理断电事件: orderId={}, eleCode={}", orderId, eleCode);
        // 这里可以添加断电处理逻辑
    }
}